import {
  Component,
  AfterViewInit,
  ChangeDetectorRef,
  ElementRef,
  ViewChild,
  OnInit,
  ChangeDetectionStrategy,
  TemplateRef,
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ICONS_DEFINE, MessageService, ModalService } from '@iux/live';
import { Subject } from 'rxjs';
import { remove as _remove } from 'lodash';
import { Common, I18NService } from 'cxd/shared';
import { environment } from 'projects/cxd/src/environments/environment';

@Component({
  selector: 'app-icon-list',
  templateUrl: './icon-list.component.html',
  styleUrls: ['./icon-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class IconListComponent implements OnInit, AfterViewInit {
  lang: string;
  label = this.i18n.get('batch_selection');

  common: Array<string> = [];
  operate: Array<string> = [];
  business: Array<string> = [];
  illustration: Array<string> = [];
  subject = new Subject<any>();

  visible: boolean = false;
  selected: number = 0;
  isCustomized: boolean = false;
  selectedIcon: string;
  selectedIcons: string[] = [];
  selectedColor: string = '#000000';
  colorCards: Array<string> = ['#ffffff', '#000000', '#6c7280', '#cccccc', '#6c92fa', '#ff4c4c'];

  @ViewChild('DownloadModalTpl', { static: false }) DownloadModalTpl: TemplateRef<any>;

  get canDownLoad(): boolean {
    if (this.selectedIcons.length) {
      return true;
    } else {
      return false;
    }
  }

  constructor(
    public el: ElementRef,
    public http: HttpClient,
    public i18n: I18NService,
    private cdr: ChangeDetectorRef,
    private message: MessageService,
    private modalService: ModalService
  ) {}

  ngOnInit(): void {
    this.lang = this.i18n.language;
  }

  ngAfterViewInit(): void {
    Promise.resolve().then(() => {
      this.iconsResource(ICONS_DEFINE, '#live-icons-public', 'public');
      this.iconsResource('operate.svg', '#live-icons-operate', 'operate');
      this.iconsResource('business.svg', '#live-icons-business', 'business');
      this.iconsResource('illustration.svg', '#live-icons-illustration', 'illustration');

      this.subject.subscribe(res => {
        this[res.name] = res.svg;
        this.cdr.detectChanges();
      });
    });
  }

  // TODO: app中已经加载，此处无需再次加载
  iconsResource(src: string, select: string, type: string): void {
    const base = location.href.slice(0, location.href.indexOf(Common.BASE_URL));
    const svg = [];

    const getSvg = response => {
      const container = this.el.nativeElement.querySelector(select);
      container.insertAdjacentHTML('afterBegin', `<div id="live-icon-${type}" style="display:none;">${response}</div>`);
      const symbols = container.querySelectorAll('symbol');

      symbols.forEach(symbol => {
        const id = symbol.getAttribute('id');
        svg.push(id);
      });
    };

    if (type === 'public') {
      getSvg(src);
      this.common = svg;
    } else {
      const prefix = `${environment.baseUrl}`;
      const url = `${base}${prefix}assets/icon/${src}`;
      const res = this.http.get(url, { responseType: 'text', params: { $prefix: 'none' } });
      res.subscribe(response => {
        getSvg(response);
        this.subject.next({ name: type, svg });
      });
    }
  }

  getSvgSize(id: string): { width: number; height: number } {
    let height = 0;
    let width = 0;

    try {
      const symbolDom = document.querySelector(`#live-icons-container symbol#${id}`);
      const viewBox = symbolDom.attributes['viewBox'].value;
      width = viewBox.split(' ')[2];
      height = viewBox.split(' ')[3];

      return { width, height };
    } catch (e) {
      return { width, height };
    }
  }

  Customized(): void {
    this.isCustomized = !this.isCustomized;

    if (!this.isCustomized) {
      this.label = this.i18n.get('batch_selection');
    } else {
      this.label = this.i18n.get('cancel');
    }
  }

  iconCopy(id: string): void {
    const svgNode = `<svg>\n
                        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#${id}"></use>\n
                     </svg>`;
    this.copyToClipboard(svgNode);
  }

  copyToClipboard(text: string): void {
    const textArea = document.createElement('textarea');
    textArea.style.position = 'fixed';
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = '0';
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      const detail = successful ? this.i18n.get('Case_Copy_Successful_ToPaste') : this.i18n.get('Case_Copy_Fail_ToPaste');
      const severity = successful ? 'success' : 'error';
      const summary = successful ? this.i18n.get('icons_copy_success') : this.i18n.get('icons_copy_fail');
      this.message.create({
        lvType: severity,
        lvTitle: summary,
        lvContent: detail,
      });
    } catch (err) {
      this.message.create({
        lvType: 'error',
        lvTitle: this.i18n.get('icons_copy_fail'),
        lvContent: this.i18n.get('Case_Copy_Fail_ToPaste'),
      });
    }

    document.body.removeChild(textArea);
  }

  /**
   * 打开下拉面板
   */
  openDownloadModal(id: string): void {
    this.visible = true;
    this.selectedIcon = id;
    this.selectedColor = '#000000';
    this.modalService.create({
      lvModalKey: id,
      lvHeader: id,
      lvContent: this.DownloadModalTpl,
      lvFooter: null,
      lvWidth: 450,
    });
  }

  colorChange(color: string): void {
    this.selectedColor = color;
  }

  colorActive(color: string) {
    return this.selectedColor === color;
  }

  /**
   * 下载图标
   */
  downLoad(type): void {
    const symbolDom = document.querySelector(`#live-icons-container symbol#${this.selectedIcon}`);
    const svgNode = symbolDom['innerHTML'];
    const viewBox = symbolDom.attributes['viewBox'].value;
    const imgInfo = {
      type,
      height: viewBox.slice(viewBox.lastIndexOf(' ')), // this.selectedSize,
      width: viewBox.slice(0, viewBox.lastIndexOf(' ')).slice(viewBox.slice(0, viewBox.lastIndexOf(' ')).lastIndexOf(' ')),
      color: this.selectedColor,
    };
    const id = symbolDom.attributes['id'].value;
    const svgImg = `<svg width="${imgInfo.width}px" height="${imgInfo.height}px" fill="${imgInfo.color}" viewBox="${viewBox}" version="1.1" xmlns="http://www.w3.org/2000/svg">\n${svgNode}\n</svg>`;
    const data = `data:image/svg+xml,${encodeURIComponent(svgImg)}`;
    this.loadImage(data).then(img => {
      const canvas = document.createElement('canvas');
      canvas.width = img['width'];
      canvas.height = img['height'];
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      const a = document.createElement('a');
      if (type === 'svg') {
        a.href = img.src;
        a.download = `${id}.svg`; // 设定下载名称
      } else if (type === 'png') {
        a.href = canvas.toDataURL('image/png');
        a.download = `${id}.png`; // 设定下载名称
      }
      const clickEvent = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: false,
      });
      a.dispatchEvent(clickEvent);
    });
  }

  CustomizedDown(): void {
    if (!this.selectedIcons.length) {
      return;
    }
    let symbol = `<svg xmlns="http://www.w3.org/2000/svg" style="display:none;">`;
    this.selectedIcons.forEach(id => {
      const symbolDom = document.querySelector(`#live-icons-container symbol#${id}`);
      const svgDom = symbolDom['outerHTML'];
      symbol = `${symbol}\n${svgDom}`;
    });
    symbol = `${symbol}\n</svg>`;
    const data = `data:image/svg+xml,${symbol}`;
    this.loadImage(data).then(img => {
      const canvas = document.createElement('canvas');
      canvas.width = img['width'];
      canvas.height = img['height'];
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      const a = document.createElement('a');
      a.href = img.src;
      a.download = `icons.svg`; // 设定下载名称
      const clickEvent = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: false,
      });
      a.dispatchEvent(clickEvent);
      this.isCustomized = false;
      this.selectedIcons.length = 0;
      this.label = this.i18n.get('batch_selection');
    });
  }

  loadImage(url): any {
    return new Promise((resolve, reject) => {
      const image = new Image();

      image.src = url;
      image.crossOrigin = 'Anonymous';
      image.onload = function() {
        resolve(this);
      };

      image.onerror = function(err) {
        reject(err);
      };
    });
  }

  toggleCustomized(e): void {
    if (!this.selectedIcons.length) {
      this.selectedIcons.push(e);
    } else {
      const some = this.selectedIcons.some(icon => icon === e);
      if (some) {
        _remove(this.selectedIcons, icon => icon === e);
      } else {
        this.selectedIcons.push(e);
      }
    }
    this.cdr.detectChanges();
  }

  selectedIconsChange(source): void {
    this.toggleCustomized(source);
  }

  isSelected(source): boolean {
    return this.selectedIcons.some(icon => icon === source);
  }
}
